package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class SearchingForFilesByFileVisitor {
	public static void main(String[] args) throws Exception {
		String glob = "*.jpg";
		long size = 102400;
		Path fileTree = Paths.get("C:");
		SearchComplex walk = new SearchComplex(glob, size);
		EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
		Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);
	}
}

class SearchComplex implements FileVisitor {

	private final PathMatcher matcher;
	private final long accepted_size;

	SearchComplex(String glob, long accepted_size) {
		matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
		this.accepted_size = accepted_size;
	}

	private void search(Path file) throws IOException {
		Path name = file.getFileName();

		long size = (Long) Files.getAttribute(file, "basic:size");

		if (name != null && matcher.matches(name) && size <= accepted_size) {
			System.out.println("搜索文件找到: " + name + " 在 "
					+ file.toRealPath().toString() + " 大小 (字节):" + size);
		}
	}

	@Override
	public FileVisitResult postVisitDirectory(Object dir, IOException exc) {
		System.out.println("访问: " + dir);
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) {
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)
			throws IOException {
		search((Path) file);
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFileFailed(Object file, IOException exc) {
		return FileVisitResult.CONTINUE;
	}
}
